<template>
<div class="custom-search">
  <h4>
    <backBtn type="business"></backBtn>{{$t("customer.CustomerSearch.CustomizeFastSearch")}}
  </h4>
  <div class="table-wrap">
    <common-table :tableHead="tableHead" :data="tableData" :pagination="pagination" @operate="operate" @turnPage="search">
      <template slot="globalOperate">
        <el-button class="small_btn" type="text" @click.stop="addSearch"><i class="el-icon-plus"></i><span class="font-color">{{$t('public.add')}}</span ></el-button>
      </template>
    </common-table>
  </div>
  <custom-search-dialog ref="CustomSearchDialog" :type="form.type" :data="form.data" @saveForm="saveForm"></custom-search-dialog>
</div>
</template>
<script>
  import CommonTable from '../config/robotConfig/base/CommonTable.vue'
  import CustomSearchDialog from './CustomSearchDialogNew.vue'
  import backBtn from '@/components/public-modules/side-bar/BackSideBar.vue'
  export default {
    name: 'CustomSearch',
    data () {
      return {
        pagination: {
          currentPage: 0,
          count: 0,
          totalPage: 0
        },
        form: {
          type: 'add',
          data: {}
        },
        searchObj: {
          page: 1,
          limit: 10
        },
        rules: {
          name: [
            {required: true, message: this.$t('validate.required'), trigger: 'blur'}
          ]
        },
        tableData: [],
        tableHead: [
          {prop: 'name', label: this.$t('customer.CustomerSearch.name')},
          {prop: 'createUserName', label: this.$t('public.creator')},
          {prop: 'createTime', label: this.$t('public.createTime')},
          {prop: 'menuName', label: this.$t('public.menu')},
          {prop: 'operate', label: this.$t('public.operate'), special: 'operateContent'}
        ]
      }
    },
    components: {
      CommonTable,
      CustomSearchDialog,
      backBtn
    },
    methods: {
      close () {
        this.$refs.CustomSearchDialog.handleClose()
      },
      addSearch () {
        this.form.type = 'add'
        this.$refs.CustomSearchDialog.open()
      },
      operate (event) {
        let type = event.type
        let data = event.val
        //回归数组处理
        if(data.condition){
          Object.keys(data.condition).forEach(item=>{
            if(typeof data.condition[item] === 'string'||typeof data.condition[item] === 'boolean'){
              //时间的处理(兼容老数据)
              if(item=='createTime$begin'){
                data.condition['createTime'] = []
                let obj = {}
                obj['createTime$begin'] = data.condition['createTime$begin']
                obj['createTime$end'] = data.condition['createTime$end']
                data.condition['createTime'].push(obj) 
                delete data.condition['createTime$begin']
                delete data.condition['createTime$end']
              }else if(item=='processEndTime$begin'){
                data.condition['processEndTime'] = []
                let obj = {}
                obj['processEndTime$begin'] = data.condition['processEndTime$begin']
                obj['processEndTime$end'] = data.condition['processEndTime$end']
                data.condition['processEndTime'].push(obj)
                delete data.condition['processEndTime$begin']
                delete data.condition['processEndTime$end']
              }else{
                data.condition[item] = [data.condition[item]]
              }
            }
          })
        }
        this.form.data = data
        this.form.type = type
        if (type === 'delete') {
          this.deleteQuestion({_id: data._id})
        } else if (type === 'edit') {
          this.$refs.CustomSearchDialog.open()
        } else if (type === 'default') {
          this.setDefault(data)
        }
      },
      deleteQuestion (data) {
        this.$confirm(this.$t('business.businessDeleteTip'), this.$t('public.delete'), {
          confirmButtonText: this.$t('public.confirm'),
          cancelButtonText: this.$t('public.cancel'),
          cancelButtonClass: 'primary_btn',
          confirmButtonClass: 'primary_btn',
          type: 'warning'
        })
          .then(() => {
            this.$store.dispatch('removeQuickSearch', data)
              .then(resp => {
                if (resp.success) {
                  this.search()
                  this.$store.commit('business/CUSTOM_SEARCH')
                  this.refreshNewBusinessView()
                  this.$message({
                    type: 'success',
                    message: this.$t('message.deleteSucc')
                  })
                }
              })
          })
      },
      saveForm (data) {
        if (this.form.type === 'add') {
          this.$store.dispatch('addQuickSearch', data).then((res) => {
            if (res.success) {
              this.$message.success(this.$t('config.channel.saveSuccess'))
              this.search()
              this.$store.commit('business/CUSTOM_SEARCH')
              this.close()
              this.refreshNewBusinessView()
            }
          })
        } else if (this.form.type === 'edit') {
          data._id = this.form.data._id
          this.$store.dispatch('updateQuickSearch', data).then((res) => {
            if (res.success) {
              this.$message.success(this.$t('business.updateSuccess'))
              this.close()
              this.search()
              this.$store.commit('business/CUSTOM_SEARCH')
              this.refreshNewBusinessView()
            }
          })
        }
      },
      setDefault (data) {
        this.$store.dispatch('updateQuickSearch', {_id: data._id, menu: data.menu, default: data.default === 'true' ? 'false' : 'true'}).then((res) => {
          if (res.success) {
            this.$message.success(this.$t('config.channel.configSuccess'))
            this.search()
            this.$store.commit('business/CUSTOM_SEARCH')
          }
        })
      },
      search (page) {
        this.searchObj.page = typeof page === 'number' ? page : 1
        this.$store.dispatch('queryQuickSearchList', this.searchObj).then((res) => {
          if (res.success) {
            this.pagination.count = res.count
            this.pagination.currentPage = this.searchObj.page
            let list = res.data || []
            for (let i = 0; i < list.length; i++) {
              let one = list[i]
              let agent = this.$agentsMap() || {}
              let createUserName = agent[one.createUser]
              let menuName = ''
              if (createUserName) {
                createUserName = createUserName.displayName
              } else {
                createUserName = '-'
              }
              one.createUserName = createUserName
              if (one.menu === 'all') {
                menuName = this.$t('public.all')
              } else if (one.menu === 'undeal') {
                menuName = this.$t('business.undealBusiness')
              } else if (one.menu === 'my') {
                menuName = this.$t('business.myTodo')
              }
              one.menuName = menuName
              if (one.default === 'true') {
                one.operate = [{name: this.$t('public.edit'), type: 'edit'}, {name: this.$t('business.cancelDefaut'), type: 'default'}, {name: this.$t('public.delete'), type: 'delete', class: 'delete'}]
              } else {
                one.operate = [{name: this.$t('public.edit'), type: 'edit'}, {name: this.$t('business.addDefaut'), type: 'default'}, {name: this.$t('public.delete'), type: 'delete', class: 'delete'}]
              }
            }
            this.tableData = list
          }
        })
      },
      refreshNewBusinessView () {
        if (this.$store.state.isNewCardStyle.business) {
          this.$store.commit('business/SET_BUSINESS_SLIDE_LIST')
        }
      }
    },
    deactivated () {
      this.$refs.CustomSearchDialog.handleClose()
    },
    beforeMount () {
      this.$store.dispatch('getCache', {type: 'agents'}).then(() => {
        this.search()
      })
    }
  }
</script>
<style lang="stylus" scoped>
  @import "../../../assets/common.styl"
  .custom-search
    height 100%
  h4
    line-height 40px
    border-bottom 1px solid $c-border1
    padding-left 10px
    font-weight bold
  .table-wrap
    padding 30px 20px
    overflow auto
</style>
